package com.uvstu.framework.web.service;

import com.uvstu.common.upay.EncryptionUtil;
import com.uvstu.common.utils.ReadMbUtil;
import com.uvstu.common.utils.email.EmailUtil;
import com.uvstu.system.domain.SysUserRole;
import com.uvstu.system.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.uvstu.common.constant.CacheConstants;
import com.uvstu.common.constant.Constants;
import com.uvstu.common.constant.UserConstants;
import com.uvstu.common.core.domain.entity.SysUser;
import com.uvstu.common.core.domain.model.RegisterBody;
import com.uvstu.common.core.redis.RedisCache;
import com.uvstu.common.exception.user.CaptchaException;
import com.uvstu.common.exception.user.CaptchaExpireException;
import com.uvstu.common.utils.MessageUtils;
import com.uvstu.common.utils.SecurityUtils;
import com.uvstu.common.utils.StringUtils;
import com.uvstu.framework.manager.AsyncManager;
import com.uvstu.framework.manager.factory.AsyncFactory;
import com.uvstu.system.service.ISysConfigService;
import com.uvstu.system.service.ISysUserService;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;

/**
 * 注册校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysRegisterService
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 注册
     */
    public String register(RegisterBody registerBody)
    {
        String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword(), email = registerBody.getEmail();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);

        // 验证码开关
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled)
        {
            validateCaptcha(username, registerBody.getCode(), registerBody.getUuid());
        }

        if (StringUtils.isEmpty(email))
        {
            msg = "邮箱不能为空";
        }
        else if (StringUtils.isEmpty(username))
        {
            msg = "用户名不能为空";
        }
        else if (StringUtils.isEmpty(password))
        {
            msg = "用户密码不能为空";
        }
        else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            msg = "账户长度必须在2到20个字符之间";
        }
        else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            msg = "密码长度必须在5到20个字符之间";
        }
        else if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(sysUser)))
        {
            msg = "注册失败，注册账号已存在";
        }else if(userService.selectUserByEmail(email) != null)
        {
            msg = "注册失败，邮箱已存在";
        }
        else
        {
            sysUser.setEmail(email);
            sysUser.setNickName(username);
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            sysUser.setStatus("1");
            boolean regFlag = userService.registerUser(sysUser);
            if (!regFlag)
            {
                msg = "注册失败,请联系系统管理人员";
            }
            else
            {
                //查询用户
                sysUser = userService.selectUserByUserName(username);
                //添加权限
                Long[] userList = new Long[1];
                userList[0] = sysUser.getUserId();
                roleService.insertAuthUsers(3L,userList);
                //准备发送激活邮件
                //1、读取配置  2、读取模板  3、替换参数   4、激活邮件发送成功
                try{
                    //获取当前时间
                    LocalDateTime currentDateTime = LocalDateTime.now();
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-ddHH");
                    String formattedDateTime = currentDateTime.format(formatter);
                    //邮件配置和邮件格式替换
                    EmailUtil.setConfig("smtp.qq.com","邮箱","授权码");
                    String html = ReadMbUtil.readHtml("activate.html");
                    html = html.replaceAll("\\{userName\\}",username);
                    html = html.replaceAll("\\{siteTitle\\}", "支付平台");
                    html = html.replaceAll("\\{activationUrl\\}", configService.selectConfigByKey("sys.url")+"/open/api/activation?email="+ EncryptionUtil.AESencrypt(sysUser.getEmail()+"|"+formattedDateTime));
                    EmailUtil.sendEmail(sysUser.getEmail(),"支付平台",html,true);
                }catch (Exception e){
                    msg = "邮件发送失败，请稍后重试！";
                    return msg;
                }

                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success")));
            }
        }
        return msg;
    }

    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            throw new CaptchaException();
        }
    }

    /**
     * 找回密码
     * @param user
     * @return
     */
    public String forgotPwd(RegisterBody user) {
        String msg = "";
        if(StringUtils.isEmpty(user.getEmail())){
            msg = "请正确输入注册邮箱";
        }else{
            // 验证码开关
            boolean captchaEnabled = configService.selectCaptchaEnabled();
            if (captchaEnabled)
            {
                validateCaptcha(user.getEmail(), user.getCode(), user.getUuid());
            }
            SysUser sysUser = userService.selectUserByEmail(user.getEmail());
            if(sysUser == null){
                msg = "该用户不存在";
            }else if(!"0".equals(sysUser.getStatus()) || !"0".equals(sysUser.getDelFlag())){
                msg = "该用户非正常状态，无法重置密码";
            }else {
                //随机获取密码
                String password = genRandomNum(8);
                sysUser.setPassword(SecurityUtils.encryptPassword(password));
                //发送邮件
                try{
                    EmailUtil.setConfig("smtp.qq.com","邮箱","授权码");
                    String html = ReadMbUtil.readHtml("forgotpwd.html");
                    html = html.replaceAll("\\{userName\\}",sysUser.getNickName());
                    html = html.replaceAll("\\{siteTitle\\}", "支付免签平台");
                    html = html.replaceAll("\\{newPassword\\}", password);
                    EmailUtil.sendEmail(sysUser.getEmail(),"支付免签平台",html,true);
                }catch (Exception e){
                    msg = "邮件发送失败，请稍后重试！";
                    return msg;
                }
                //保存新密码
                userService.updateUser(sysUser);
            }
        }
        return msg;
    }

    /**
     * 随机数生成
     * @param num
     * @return
     */
    public String genRandomNum(int num){
        int  maxNum = 36;
        int i;
        int count = 0;
        char[] str = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
                'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
                'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
        StringBuffer pwd = new StringBuffer("");
        Random r = new Random();
        while(count < num){
            i = Math.abs(r.nextInt(maxNum));
            if (i >= 0 && i < str.length) {
                pwd.append(str[i]);
                count ++;
            }
        }
        return pwd.toString();
    }
}
